package sf.database.jdbc.type;

import sf.tools.StringUtils;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Types;

public class ArrayType implements TypeHandler<Array> {
    /**
     * array类型名称
     */
    private String typeName;

    public ArrayType(String typeName) {
        this.typeName = typeName;
    }

    public ArrayType() {
    }

    @Override
    public Array get(ResultSet rs, String columnName) throws SQLException {
        return rs.getArray(columnName);
    }

    @Override
    public Array get(ResultSet rs, int index) throws SQLException {
        return rs.getArray(index);
    }

    @Override
    public Array get(CallableStatement cs, int index) throws SQLException {
        return cs.getArray(index);
    }

    @Override
    public Array get(CallableStatement cs, String parameterName) throws SQLException {
        return cs.getArray(parameterName);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        if (value instanceof Array) {
            rs.updateArray(columnLabel, (Array) value);
        } else if (StringUtils.isNotBlank(typeName) && value instanceof Object[]) {
            Array array = rs.getStatement().getConnection().createArrayOf(typeName, (Object[]) value);
            rs.updateArray(columnLabel, array);
        }
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        if (value instanceof Array) {
            rs.updateArray(columnIndex, (Array) value);
        } else if (StringUtils.isNotBlank(typeName) && value instanceof Object[]) {
            Array array = rs.getStatement().getConnection().createArrayOf(typeName, (Object[]) value);
            rs.updateArray(columnIndex, array);
        }
    }

    @Override
    public Object set(PreparedStatement ps, Object obj, int index) throws SQLException {
        if (null == obj) {
            ps.setNull(index, getSqlType());
        } else if (obj instanceof Array) {
            ps.setArray(index, (Array) obj);
        } else if (StringUtils.isNotBlank(typeName) && obj instanceof Object[]) {
            Array array = ps.getConnection().createArrayOf(typeName, (Object[]) obj);
            ps.setArray(index, array);
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        throw new SQLFeatureNotSupportedException("not support");
    }

    @Override
    public Class<Array> getDefaultJavaType() {
        return Array.class;
    }

    @Override
    public int getSqlType() {
        return Types.ARRAY;
    }

    public String getTypeName() {
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
}
